import { app, BrowserWindow, ipcMain, protocol, shell } from 'electron'
import { join } from 'path'
import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { DataBaseManager } from './db/DataBaseManager'
import { Handler } from './handler'
import * as path from 'node:path'

function createWindow(): void {
  // Create the browser window.

  const mainWindow = new BrowserWindow({
    minWidth: 500,
    minHeight: 400,
    width: 900,
    height: 670,
    show: false,
    frame: false,
    title: 'electron',
    autoHideMenuBar: true,
    icon: join(__dirname, '../../resources/icon.png'),
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })
  mainWindow.on('maximize', () => {
    console.log('maximize')
    mainWindow.webContents.send('onMaximize')
  })

  mainWindow.on('unmaximize', () => {
    console.log('unmaximize')
    mainWindow.webContents.send('onUnmaximize')
  })

  ipcMain.on('window.close', () => {
    mainWindow.close()
  })
  ipcMain.on('window.maximize', () => {
    if (mainWindow.isMaximized()) {
      mainWindow.restore()
    } else {
      mainWindow.maximize()
    }
  })

  ipcMain.on('window.minimize', () => {
    mainWindow.minimize()
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.maximize()
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    console.log(process.env['ELECTRON_RENDERER_URL'])
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + '?redirect=home')
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'), { search: 'redirect=index' })
  }
}
app.commandLine.appendSwitch('no-sandbox');
const handler = new Handler()
handler.initHandler(ipcMain)

app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('electronDemo.mammoth_work@163.com')
  // 注册自定义通道，映射至软件data/file目录下，可以自定义为其他目录，也可以修改为绝对路径
  protocol.registerFileProtocol('appfile', (request, callback) => {
    let relativePath = request.url.replace('appfile://', '')
    if (relativePath.indexOf('/appfile/') != -1) {
      relativePath = relativePath.substring(
        relativePath.lastIndexOf('/appfile/') + '/appfile/'.length
      )
    }
    if (relativePath.indexOf('?') != -1) {
      relativePath = relativePath.substring(0, relativePath.indexOf('?'))
    }
    let relativeServerPath
    if (app.isPackaged) {
      relativeServerPath = '../../../../data/file'
    } else {
      relativeServerPath = '../../data/file'
    }
    const pathR = path.join(__dirname, relativeServerPath, relativePath)
    console.log(pathR)
    callback(decodeURI(path.normalize(pathR)))
  })

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  DataBaseManager.init().then(() => {
    createWindow()
  })

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
